//
//  MyDownloader.swift
//  sandboxapp
//
//  Created by 杨岑 on 2018/8/13.
//  Copyright © 2018年 杨岑. All rights reserved.
//

import Cocoa

class MyDownloader {
    func handleClientError(_ error: Error?) -> Void {
        print("Got error: \(String(describing: error))")
    }
    
    func handleServerError(_ response: URLResponse?) -> Void {
        print("Got server error: \(String(describing: response))")
    }
    
    func startLoad(_ url: String) {
        print("Downloading \(url)")
        let url = URL(string: url)!
        print("Creating task \(url)")
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            print("Got response \(url)")
            
            if let error = error {
                self.handleClientError(error)
                return
            }
            guard let httpResponse = response as? HTTPURLResponse,
                (200...299).contains(httpResponse.statusCode) else {
                    self.handleServerError(response)
                    return
            }
            if let mimeType = httpResponse.mimeType, mimeType == "text/html",
                let data = data,
                let string = String(data: data, encoding: .utf8) {
                DispatchQueue.main.async {
                    print("Downlaoded HTML content:\n\(string)")
                }
            }
        }
        print("Resuming task \(url)")
        task.resume()
    }
}
